package TableEditions;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

import TableAdditions.main;
import Tables.PersonelTableInterface;
import Utility.Personnel;
import Utility.Vehicle;

public class PersonelEdition extends JFrame {
	
    private JTextField personelNameField;
    private JTextField personelPhoneField;
    private JTextField addressField;
    private JComboBox vehicleNameCombo;
    
    int[] personelId;
    Vehicle[] vehicle;
    int driverId2=0;
    int selectedVehicleIndex=0;
    int selectedIndex=0;
    String exPlate="Araç Plaka";
    String newPlate;
    
	public String personelName;
	public String address;
	public String personelPhone;
	public String jobName;
	public String vehicleName;
    int selectedVehicle=0;
	public static boolean driverDuplicateFlag=true;
	
	
    private JButton customerEditButton;
    PersonelTableInterface cti;
    
    public PersonelEdition(final PersonelTableInterface cti,final Personnel personel) {
    	
		super("Personel Düzenleme Ekranı");
		this.cti = cti;
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setSize(600,200);
		getContentPane().setLayout(null);
		
		JLabel codeLabel = new JLabel("Personel Adı");
		codeLabel.setBounds(20, 10, 90, 20);
		getContentPane().add(codeLabel);
		
		personelNameField = new JTextField();
		personelNameField.setBounds(124, 11, 115, 20);
		personelNameField.setText(personel.getPersonnelName());
		getContentPane().add(personelNameField);
		personelNameField.setColumns(10);
		
		JLabel authorityLabel = new JLabel("Telefon");
		authorityLabel.setBounds(20, 40, 90, 20);
		getContentPane().add(authorityLabel);
		
		personelPhoneField = new JTextField();
		personelPhoneField.setBounds(124, 43, 115, 20);
		personelPhoneField.setText(personel.getPersonnelPhone());
		getContentPane().add(personelPhoneField);
		personelPhoneField.setColumns(10);
		
		JLabel nameLabel = new JLabel("Adres");
		nameLabel.setBounds(270, 10, 90, 20);
		getContentPane().add(nameLabel);
		
		addressField = new JTextField();
		addressField.setBounds(370, 10, 115, 20);
		addressField.setText(personel.getPersonnelAddress());
		getContentPane().add(addressField);
		addressField.setColumns(10);
		
		selectedVehicle=personel.getPersonnelVehicleId();
		
		vehicleNameCombo = new JComboBox();
		vehicleNameCombo.setBounds(370, 40, 115, 20);
		getContentPane().add(vehicleNameCombo);
		   try {
			   Connection conn = null;
		        Statement stmt = null;
		        ResultSet rss = null;

		        String url = "jdbc:mysql://localhost:3306/mydb";
		        String user = "root";
		        String password = "qweasdzxc";
		        
		        conn = (Connection) DriverManager.getConnection(url, user, password);
				stmt = (Statement) conn.createStatement();
				


					
					
					
					vehicleNameCombo.addItem("Araç Plaka");
					rss=stmt.executeQuery("SELECT * from vehicle WHERE activity='1'");
					
					int vehicleCounter=0;
					while(rss.next()){
						vehicleCounter++;
						
					}
					if(vehicleCounter!=0){
						rss.first();
					vehicle = new Vehicle[vehicleCounter];
					int m=0;
					if(rss.getInt("vehicle_availability")>0 || rss.getInt("vehicle_id")==selectedVehicle)
					{
						
					vehicle[m]=new Vehicle();
					vehicleNameCombo.addItem(rss.getString("vehicle_licence_plate"));
					vehicle[m].setVehicleId(rss.getInt("vehicle_id"));
					vehicle[m].setVehicleLicencePlate(rss.getString("vehicle_licence_plate"));
					
					if(rss.getInt("vehicle_id")==selectedVehicle){
						selectedVehicleIndex=m+1;
						exPlate=vehicle[m].getVehicleLicencePlate();
					}
					
					m++;
					}
				
					
				
					while(rss.next()){
						if(rss.getInt("vehicle_availability")>0 || rss.getInt("vehicle_id")==selectedVehicle )
						{
								
							vehicle[m]=new Vehicle();
							vehicleNameCombo.addItem(rss.getString("vehicle_licence_plate"));
							vehicle[m].setVehicleId(rss.getInt("vehicle_id"));
							vehicle[m].setVehicleLicencePlate(rss.getString("vehicle_licence_plate"));
							
							if(rss.getInt("vehicle_id")==selectedVehicle){
								selectedVehicleIndex=m+1;
								exPlate=vehicle[m].getVehicleLicencePlate();
							}
							m++;
						}
					}
					}
				
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		JLabel address1Label = new JLabel("Araç");
		address1Label.setBounds(270, 40, 90, 20);
		getContentPane().add(address1Label);
		
		vehicleNameCombo.setSelectedIndex(selectedVehicleIndex);
		
		vehicleNameCombo.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent event) {
				// TODO Auto-generated method stub
				
				JComboBox comboBox = (JComboBox) event.getSource();
			     
                //
                // Print the selected items and the action command.
                //
                Object selected = comboBox.getSelectedItem();
                System.out.println("Selected Item  = " + selected);
              
                
                selectedIndex=comboBox.getSelectedIndex();
                System.out.println("selected index="+selectedIndex);
                newPlate=(String) selected;
                /*System.out.println("selected vehicle plate : "+vehicle[selectedIndex-1].getVehicleLicencePlate());
                System.out.println("selected vehicle id: "+vehicle[selectedIndex-1].getVehicleId());*/
                
				
			}
		});
		
		
		
		
		customerEditButton = new JButton("Düzenle");
		customerEditButton.setForeground(Color.BLACK);
		customerEditButton.setFont(new Font("Arial", Font.BOLD, 16));
		customerEditButton.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
			    
				
				
				personelName=personelNameField.getText();
				address=addressField.getText();
				personelPhone=personelPhoneField.getText();	
				vehicleName=(String) vehicleNameCombo.getSelectedItem();
				int vNum=-1;
	
				
				
				System.out.println("Ready to execute sql");
				 	Connection con = null;
			        Statement st = null;
			        ResultSet rs = null;

			        String url = "jdbc:mysql://localhost:3306/mydb";
			        String user = "root";
			        String password = "qweasdzxc";

			        try {
			            con = (Connection) DriverManager.getConnection(url, user, password);
			            st = (Statement) con.createStatement();
			            //st.executeUpdate("INSERT INTO job " + "VALUES (1, 'deneme')");
			         //   st.executeUpdate("UPDATE customer SET customer_phone='0554755' WHERE customer_name='rehber';");
			           
			            int i=0;
			            if(!vehicleName.equals("Araç Plaka") && !vehicleName.equals(exPlate) ){
			            rs=st.executeQuery("SELECT vehicle_id from vehicle WHERE vehicle_licence_plate='"+newPlate+"' and activity='1'");
			            while(rs.next())
			            {
			            	i++;
			            	vNum=rs.getInt("vehicle_id");
			            }
			            }else{
			            	vNum=-1;
			            }
			            
			            
			            
						
								
						String insert="UPDATE personel SET personel_name='"+personelName+"',personel_phone='"+personelPhone+"',personel_address='"+address+"'," +
								"personel_vehicle_id='"+vNum+"' where personel_id='"+personel.getPersonnelId()+"'";
						
						int messageType = JOptionPane.PLAIN_MESSAGE;
						
						if(true){
							st.executeUpdate(insert);
							if(vNum!=-1){
								System.out.println("New plate added = "+newPlate+" personel id= "+personel.getPersonnelId());
								st.executeUpdate("UPDATE vehicle SET vehicle_availability=0 ,vehicle_driver_id='"+personel.getPersonnelId()+"'where vehicle_licence_plate='"+newPlate+"'");
								
								if(!exPlate.equals(newPlate) && !exPlate.equals("Araç Plaka")){
									st.executeUpdate("UPDATE vehicle SET vehicle_availability=1,vehicle_driver_id=-1 where vehicle_licence_plate='"+exPlate+"'");
								}
							}
							else{
								st.executeUpdate("UPDATE vehicle SET vehicle_availability=1,vehicle_driver_id=-1 where vehicle_licence_plate='"+exPlate+"'");
							}
							
							JOptionPane.showMessageDialog(null, "Güncelleme Yapıldı", "Uyarı!!", messageType);
						}
			            //addTa(newRow[0]);
			            //st.executeUpdate("DELETE FROM job");
			       
						
						
			          
			           
			           con.close(); 
			        } catch (SQLException ex) {
			            Logger lgr = Logger.getLogger(main.class.getName());
			            lgr.log(Level.SEVERE, ex.getMessage(), ex);

			        } finally {
			            try {
			                if (rs != null) {
			                    rs.close();
			                }
			                if (st != null) {
			                    st.close();
			                }
			                if (con != null) {
			                    con.close();
			                }

			            } catch (SQLException ex) {
			                Logger lgr = Logger.getLogger(main.class.getName());
			                lgr.log(Level.WARNING, ex.getMessage(), ex);
			            }
			        }
			        
			        // this will make sure WindowListener.windowClosing() et al. will be called.
			      //  WindowEvent wev = new WindowEvent(this, WindowEvent.WINDOW_CLOSING);
			        //Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);

			        // this will hide and dispose the frame, so that the application quits by
			        // itself if there is nothing else around. 
			        cti.addNewItem();
			        setVisible(false);
			        dispose();
			}});
		
		customerEditButton.setBounds(375, 102, 120, 25);
		getContentPane().add(customerEditButton);
		
		
	setVisible(true);  
		
	}
  
   /* public static void main(String[] args) {
		new PersonelAddition();
	}*/

}
